package com.maixy.shorturldemo.service;

import com.maixy.shorturldemo.entity.UrlCenter;
import com.maixy.shorturldemo.mapper.UrlCenterMapper;
import com.maixy.shorturldemo.utils.ChangeBaseUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @ClassName UrlCenterService
 * @Description TODO
 * @Date 2021/7/1 19:02
 * @Author maixingyu
 */
@Service
public class UrlCenterService {
    @Resource
    private UrlCenterMapper urlCenterMapper;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public String createShortUrl(String longUrl) {
        UrlCenter urlCenter = new UrlCenter();
        urlCenter.setLongUrl(longUrl);
        //根据id生成短链接的base62
        urlCenterMapper.insert(urlCenter);
        //更新数据
        String urlKey = ChangeBaseUtils.radix10To62(urlCenter.getId());
        String shortUrl = "http://localhost:10009/".concat(urlKey);
        urlCenter.setShortUrl(shortUrl);
        urlCenterMapper.updateById(urlCenter);
        //返回新的url
        return shortUrl;
    }

    public String getLongUrl(String urlKey) {
        Long id = ChangeBaseUtils.radix62To10(urlKey);
        UrlCenter urlCenter = urlCenterMapper.selectById(id);
        if (null == urlCenter) {
            throw new NullPointerException();
        }
        return urlCenter.getLongUrl();
    }
}
